<template>
  <view>
    <view class="header-nav">
      <view class="left-item">
        <image src="/static/images/logo.png" alt="" />
      </view>
      <view class="right-item">
        <view class="wallet" v-if="text !== ''">
          <view class="point"></view>
          <view @click="toSing" class="login">{{ text }}</view>
        </view>
        <view class="wallet" v-else>
          <view class="point-red"></view>
          <view @click="toLogin" class="login">{{ i18n.h012 }}</view>
        </view>
        <view class="lang" @click="toPage('/pages/home/language')">
          <image src="/static/images/lang.png" alt="" />
        </view>
      </view>
    </view>
    <loginModal ref="loginModalref"></loginModal>

    <!-- 注册码  绑定上级-->
    <modal
      :show="addressModel"
      custom
      :maskClosable="false"
      :title="'绑定推荐人'"
      :padding="'32rpx'"
      width="646rpx"
    >
      <view class="spodAds-mod">
        <view class="tit">{{ i18n.h126 }}</view>
        <view class="address-input">
          <u--textarea
            placeholder="Please enter"
            placeholderStyle="color:#5D5D5D"
            v-model="Recommenderaddres"
            border="none"
            :confirmType="null"
            clearable
          ></u--textarea>
        </view>
        <view class="confirm" @click="setbind()">{{ i18n.h5 }}</view>
      </view>
    </modal>
  </view>
</template>
<script>
import { USDT_contracts, Models_contracts } from "@/common/wb3";
import modal from "../../components/modal/modal.vue";
import loginModal from "../../components/loginModal/loginModal.vue";
import {
  metamasklogin,
  getcode,
  getRandomNum,
  follow,
} from "../../api/module/home";
import Web3 from "web3";
import qs from "qs";
export default {
  mixins: [],
  components: {
    modal,
    loginModal,
  },
  props: {
    navTitle: String,
    showMenu: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      user: "",
      text: "",
      userAccount: "",
      usreaddress: "",
      Code: "", // 签名
      IsSignUp: "", // 是否注册
      signature: "",
      Recommenderaddres: "",
      codevalue: "0x0F5cdbB3c670dFDCf5b4F862e978712354c8279c",
      addressModel: false, //填写注册码
      isBind: false, //是否绑定成功
      memberId: "",
      show: false,
      activeMenukey: "",

      Service: "",
    };
  },

  created() {},
  onLoad(options) {},
  watch: {},
  computed: {
    i18n() {
      return this.$t("home");
    },
  },

  mounted() {
    this.usreaddress = uni.getStorageSync("user")
      ? uni.getStorageSync("user")
      : "";
    this.userAccount = uni.getStorageSync("user")
      ? uni.getStorageSync("user")
      : "";
    this.text = this.usreaddress == "" ? "" : this.getCaption(this.usreaddress);
    this.toLogin();
    this.isBindReferrer();
  },

  activated() {
    this.usreaddress = uni.getStorageSync("user")
      ? uni.getStorageSync("user")
      : "";
    this.userAccount = uni.getStorageSync("user")
      ? uni.getStorageSync("user")
      : "";
    this.text = this.usreaddress == "" ? "" : this.getCaption(this.usreaddress);
    this.toLogin();
    this.isBindReferrer();
  },
  watch: {
    usreaddress: function (a, b) {},
    deep: true,
  },
  methods: {
    async toLogin() {
      //登录
      var Web3 = require("web3");

      const web3s = new Web3(Web3.givenProvider);
      const networkId = await web3s.eth.net.getId();
      console.log("networkId", networkId);

      if (networkId !== 9070) {
        return this.switchChain();
      }
      // BSC正式链的网络ID是56
      // this.isBSCMainnet = networkId === 56;
      // console.log(networkId, "networkId");
      // if (networkId !== 56) {
      //   return modal.toast("Please switch to the BSC official chain", {
      //     icon: "error",
      //   });
      // }

      // 授权获取账户
      const web3 = new Web3(window.ethereum);
      const accounts = await ethereum.enable();
      console.log("获取账户---", accounts);
      // console.log("this.usreaddress", this.usreaddress);
      if (this.usreaddress != "" && this.usreaddress != accounts[0]) {
        uni.clearStorage();
        uni.clearStorageSync();
        location.reload();
        return;
      }
      if (this.usreaddress == accounts[0]) {
        return;
      }
      // 获取签名随机数
      this.userAccount = accounts[0];

      let getNum = await getcode(qs.stringify({ address: this.userAccount }));
      console.log("签名随机数字----", getNum);
      if (getNum.code == 0) {
        this.Code = getNum.data.Code;
        // this.IsSignUp = getNum.data.IsSignUp;
        let _this = this;
        let isPersonal = await web3.eth.personal.sign(
          _this.Code,
          _this.userAccount,
          ""
        );
        if (isPersonal) {
          console.log("拉起授权成功-----", isPersonal);
          _this.signature = isPersonal;
          _this.subMitLogo();
        }
      }
    },

    // 尝试切换链
    async switchChain() {
      const web3 = new Web3(window.ethereum);
      const ethereum = window.ethereum;
      console.log("走了");
      // 你建议的链的配置
      const chainId = "0x236e";
      const chainName = "Akashic";
      const rpcUrl = "https://rpc-mainnet.akashicrecords.io";
      const nativeCurrency = {
        name: "AKC",
        symbol: "AKC",
        decimals: 18,
      };
      const blockExplorerUrl = "https://blockscan-mainnet.akashicrecords.io"; // 区块浏览器
      try {
        await ethereum.request({
          method: "wallet_switchEthereumChain",
          params: [
            {
              chainId,
            },
          ],
        });
        console.log("切换链成功");
        window.location.reload();

        // uni.reLaunch({
        //   url: "/pages/home/index",
        // });
      } catch (switchError) {
        // 如果链没有添加，则提示添加该链
        if (switchError.code === 4902) {
          try {
            await ethereum.request({
              method: "wallet_addEthereumChain",
              params: [
                {
                  chainId,
                  chainName,
                  rpcUrls: [rpcUrl],
                  nativeCurrency,
                  blockExplorerUrls: [blockExplorerUrl],
                },
              ],
            });
            console.log("链已添加并切换成功");
            window.location.reload();

            // uni.reLaunch({
            //   url: "/pages/home/index",
            // });
          } catch (addError) {
            console.error("添加链失败", addError);
            uni.showToast({
              icon: "none",
              title: this.$t("home.h138"),
            });
          }
        }
      }
    },

    //查询上级是否绑定
    async isBindReferrer() {
      console.log("查询上级-----", this.userAccount);
      console.log("查询上级typeof-----", typeof this.userAccount);

      try {
        let res = await Models_contracts.methods
          .getSuperior(this.userAccount)
          .call();

        console.log("是否绑定-结果", res);
        if (res == "0x0000000000000000000000000000000000000000") {
          // /* 从链接截取邀请码  */
          this.Recommenderaddres = window.location.href.split("id=")[1] || "";
          if (this.Recommenderaddres.indexOf("&") != -1) {
            this.Recommenderaddres = this.Recommenderaddres.split("&")[0];
          }
          /* 弹出注册码框 */
          this.addressModel = true;
        }
      } catch (error) {
        console.log("查询绑定失败-----", error);
      }
    },
    //绑定上级
    async setbind() {
      console.log("this.Recommenderaddres", this.Recommenderaddres);

      if (this.Recommenderaddres == "") {
        return;
      }
      let a = "0xd15d7D5b4A89105301F68Ca2a50679eAFe8f7cd0";
      if (this.Recommenderaddres.toLowerCase() != a.toLowerCase()) {
        let res = await Models_contracts.methods
          .getSuperior(this.Recommenderaddres)
          .call();

        if (res == "0x0000000000000000000000000000000000000000") {
          uni.showToast({
            icon: "none",
            // title: "绑定失败",
            title: this.$t("home.h022"),
          });
          return;
        }
      }

      uni.showLoading({
        // title: "绑定中",
        title: this.$t("home.h21"),
        mask: true,
      });
      console.log("this.userAccount", this.userAccount);
      console.log("this.Recommenderaddres", this.Recommenderaddres);
      try {
        let result = await Models_contracts.methods
          .bindSuperior(this.Recommenderaddres)
          .send({
            from: this.userAccount,
          });
        if (result) {
          console.log("绑定推荐人成功-----", result);
          this.addressModel = false;
          uni.hideLoading();
          uni.showToast({
            // title: "绑定成功",
            title: this.$t("home.h23"),
          });
          setTimeout(function () {
            location.reload();
          }, 800);
        }
      } catch (error) {
        console.log("绑定推荐人失败-----", error);
        uni.hideLoading();
        uni.showToast({
          icon: "none",
          // title: "绑定失败",
          title: this.$t("home.h22"),
        });
      }
    },

    async subMitLogo() {
      console.log("登录");
      // 登录中
      uni.showLoading({
        // title: "登录中",
        title: this.$t("home.h01"),
        mask: true,
      });

      //拉起-登录
      console.log("授权用户", this.userAccount);
      let obj = {
        address: this.userAccount,
        // invitecode: this.Recommenderaddres,
        signature: this.signature,
      };
      metamasklogin(qs.stringify(obj)).then((v) => {
        console.log("metamasklogin-----", v);
        if (v.code == 0) {
          uni.hideLoading();
          uni.showToast({
            title: this.$t("home.h13"),
            // title: "登录成功",
            duration: 2000,
            icon: "success",
          });

          this.usreaddress = this.userAccount;

          uni.setStorageSync("user", this.userAccount);
          this.text =
            this.usreaddress == "" ? "" : this.getCaption(this.usreaddress);
          uni.setStorageSync("Id", v.data.Id);
          uni.setStorageSync("Token", v.data.Token);
          uni.setStorageSync("code", this.Code);
          // this.isBindReferrer(); //登录成功后-查询上级是否绑定
          setTimeout(function () {
            location.reload();
          }, 800);
        } else {
          uni.hideLoading();
          uni.showToast({
            title: v.message,
            duration: 2000,
            icon: "error",
          });
        }
      });
    },

    toInvite() {
      this.$refs.loginModalref.showInvite();
    },

    singOutModel() {
      this.$refs.loginModalref.showLoginOut();
    },
    toSing() {
      this.$refs.loginModalref.showLoginOut();
    },
    initLang() {
      const langval = uni.getStorageSync("akcLang")
        ? uni.getStorageSync("akcLang")
        : "zh";
      const langvs = uni.getStorageSync("lang")
        ? uni.getStorageSync("lang")
        : "zh";

      uni.setStorageSync("ininLang", langval);
      uni.setStorageSync("lang", langvs);
    },
    toPage(path) {
      if (path !== "") {
        uni.navigateTo({
          url: path,
        });
      }
    },
    toLink(path) {
      if (path !== "") {
        window.open(path, "_blank");
      }
    },
    getCaption(strings) {
      var strLength = strings.length;
      var shortName = strings.substring(0, 3);
      var shortName2 = strings.substring(strLength - 5, strLength);
      let str = `${shortName}...${shortName2}`;
      return str;
    },
  },
};
</script>
<style lang="scss" scoped>
.header-nav {
  /* #ifdef H5 */
  padding: 32rpx 32rpx 32rpx;
  /* #endif */

  /* #ifdef APP-PLUS */
  padding: 132rpx 32rpx 32rpx;
  /* #endif */

  // background: #000000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left-item {
    display: flex;
    align-items: center;
    image {
      width: 50rpx;
      height: 56rpx;
    }
  }
  .right-item {
    display: flex;
    align-items: center;
    .wallet {
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      border-radius: 16rpx;
      height: 64rpx;
      line-height: 64rpx;
      width: 184rpx;
      background: #f5f3fe;
      .login {
        text-align: center;
        color: #835bf1;
        font-size: 26rpx;
        font-weight: 500;
      }
    }
    .lang {
      margin-left: 32rpx;
      image {
        width: 48rpx;
        height: 48rpx;
        border-radius: 50%;
      }
    }
  }
}
.popup-conters {
  padding: 64rpx 54rpx;
  min-width: 300rpx;

  .menu-header {
    padding: 40rpx 0 90rpx;
    display: flex;
    justify-content: space-between;
    .closeIcon {
      width: 64rpx;
      height: 64rpx;
      line-height: 64rpx;
      background: #000000;
      box-shadow: 0px 20px 20px 2px rgba(0, 0, 0, 0.15);
      font-weight: 500;
      font-size: 18rpx;
      color: #ffffff;
      border-radius: 50%;
      text-align: center;
    }
    .langIcon {
      width: 64rpx;
      height: 64rpx;
      line-height: 64rpx;
      background: #000000;
      box-shadow: 0px 20px 20px 2px rgba(0, 0, 0, 0.15);
      font-weight: 500;
      font-size: 18rpx;
      color: #ffffff;
      border-radius: 50%;
      text-align: center;
    }
  }

  .row-menu {
    width: 368rpx;
    padding: 116rpx 0;
    border-top: 2rpx solid rgba(112, 112, 112, 0.42);
    border-bottom: 2rpx solid rgba(112, 112, 112, 0.42);
    .row-item {
      margin-bottom: 34rpx;
      view {
        text-align: right;
        font-weight: 600;
        font-size: 30rpx;
        color: #222222;
      }
    }
  }
  .customer {
    margin-top: 52rpx;
    margin-bottom: 388rpx;
    display: flex;
    align-items: center;
    justify-content: end;
    text {
      font-size: 22rpx;
      color: #222222;
      margin-top: -15rpx;
    }
    image {
      width: 86rpx;
      height: 86rpx;
    }
  }
  .copyrights {
    font-weight: 400;
    font-size: 20rpx;
    color: #a6a6a6;
    text-align: right;
  }
}
</style>
